/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.service.impl;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.business.domain.FixedCosts;
import me.zhengjie.business.domain.Fymx;
import me.zhengjie.business.domain.vo.FymxMrzjVo;
import me.zhengjie.business.domain.vo.ZyryVo;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.business.repository.FymxRepository;
import me.zhengjie.business.service.FymxService;
import me.zhengjie.business.service.dto.FymxDto;
import me.zhengjie.business.service.dto.FymxQueryCriteria;
import me.zhengjie.business.service.mapstruct.FymxMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.math.BigDecimal;
import java.util.*;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author xiahongbo
* @date 2022-08-17
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class FymxServiceImpl implements FymxService {

    @Autowired
    private EntityManager entityManager;

    private final FymxRepository fymxRepository;
    private final FymxMapper fymxMapper;

    @Override
    public Map<String,Object> queryAll(FymxQueryCriteria criteria, Pageable pageable){
        Page<Fymx> page = fymxRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(fymxMapper::toDto));
    }

    @Override
    public List<FymxDto> queryAll(FymxQueryCriteria criteria){
        return fymxMapper.toDto(fymxRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public FymxDto findById(Long bisFymxId) {
        Fymx fymx = fymxRepository.findById(bisFymxId).orElseGet(Fymx::new);
        ValidationUtil.isNull(fymx.getBisFymxId(),"Fymx","bisFymxId",bisFymxId);
        return fymxMapper.toDto(fymx);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FymxDto create(Fymx resources) {

        String iscw = fymxRepository.queryCw(resources.getBisFymxJzdjId(), resources.getBisFymxKfrq());
        log.info("[FymxServiceImpl - create]--------------- 新增账单 - start");
        if(iscw != null) {
            if((iscw.indexOf("20160301") != -1 || iscw.indexOf("ZHBX036") != -1 || iscw.indexOf("ZHBX039") != -1) &&
                    "20160301,ZHBX036,ZHBX039".indexOf(resources.getBisFymxYbypbm()) != -1) {
                log.info("[FymxServiceImpl - create]--------------- 新增账单 - 已存在床位：{} ", iscw);
                throw new BadRequestException("费用明细中，已存在床位费");
            }
        }

        BigDecimal djBigDecimal = resources.getBisFymxDj();
        BigDecimal slBigDecimal = new BigDecimal(resources.getBisFymxSl());
        BigDecimal zjBigDecimal = djBigDecimal.multiply(slBigDecimal);

        String datetime = DateUtil.format(new Date(), "yyyyMMddHHmmss");

        int ramdom1 = (int)((Math.random()*9+1)*1000);
        String cfh = datetime + ramdom1;

        // 总价
        resources.setBisFymxZj(zjBigDecimal);
        // 处方号
        resources.setBisFymxCfh(cfh);
        // 交易类型
        resources.setBisFymxYjlx("1");
        // 处方药标志（1处方药 0非处方药）
        resources.setBisFymxCfybz("0");
        // 包装数量
        resources.setBisFymxBzsl(1l);

        return fymxMapper.toDto(fymxRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Fymx resources) {
        Fymx fymx = fymxRepository.findById(resources.getBisFymxId()).orElseGet(Fymx::new);
        ValidationUtil.isNull( fymx.getBisFymxId(),"Fymx","id",resources.getBisFymxId());
        fymx.copy(resources);


        BigDecimal djBigDecimal = fymx.getBisFymxDj();
        BigDecimal slBigDecimal = new BigDecimal(fymx.getBisFymxSl());
        BigDecimal zjBigDecimal = djBigDecimal.multiply(slBigDecimal);

        // 总价
        fymx.setBisFymxZj(zjBigDecimal);
        fymxRepository.save(fymx);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long bisFymxId : ids) {
            fymxRepository.deleteById(bisFymxId);
        }
    }

    @Override
    public void download(List<FymxDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (FymxDto fymx : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<FymxMrzjVo> groupByKfrq2Zj(Long jzid) {
        List<Object> list = fymxRepository.groupByKfrq2Zj(jzid);
        List<FymxMrzjVo> vos = new ArrayList<>();
        for (Object obj : list) {
            Object[] arr = (Object[]) obj;

            FymxMrzjVo vo = new FymxMrzjVo();
            vo.setContent(((BigDecimal)arr[0]).toPlainString());
            vo.setKfrq((String)arr[1]);
            vos.add(vo);
        }
        return vos;
    }

    /**
     * 固费记账
     * @param resources
         */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createFixedCosts(Fymx resources) {
     //   fymxRepository.createFixedCosts(resources.getBisFymxKfrq(), resources.getBisFymxJzdjId());
        log.info("createFixedCosts:", resources);
        String adlPcSql = "insert into bis_fymx " +
                "  (bis_fymx_id, " +
                "   bis_fymx_jzdj_id, " +
                "   bis_fymx_jzdj_lsh, " +
                "   bis_fymx_ybkh, " +
                "   bis_fymx_yjlx, " +
                "   bis_fymx_yyypbm, " +
                "   bis_fymx_cfh, " +
                "   bis_fymx_kfrq, " +
                "   bis_fymx_ybypbm, " +
                "   bis_fymx_mc, " +
                "   bis_fymx_dj, " +
                "   bis_fymx_sl, " +
                "   bis_fymx_zj, " +
                "   bis_fymx_jx, " +
                "   bis_fymx_jl, " +
                "   bis_fymx_sypc, " +
                "   bis_fymx_yf, " +
                "   bis_fymx_zxks, " +
                "   bis_fymx_zxts, " +
                "   bis_fymx_ybsflb, " +
                "   bis_fymx_spr, " +
                "   bis_fymx_zdxmjkm, " +
                "   bis_fymx_ysxm, " +
                "   bis_fymx_jbr, " +
                "   bis_fymx_yysflb, " +
                "   bis_fymx_dw, " +
                "   bis_fymx_gg, " +
                "   bis_fymx_cfybz, " +
                "   bis_fymx_bzsl, " +
                "   bis_fymx_yl, " +
                "   bis_fymx_ypdzjgm, " +
                "   lrsj, " +
                "   sfyx, " +
                "   bis_fymx_grbh) " +
                "  select sequence_fymx.nextval, " +
                "         t2.bis_jzdj_id, " +
                "         t2.bis_jzdj_lsh, " +
                "         t3.bis_zhsq_ybkh, " +
                "         '1' jylx, " +
                "         t1.bis_fixed_costs_ypbm, " +
                "         to_char(sysdate, 'yyyymmddhh24miss') || " +
                "         lpad(trunc(dbms_Random.Value(0, 10000)), 4, '0') cfh, " +
                "         '"+resources.getBisFymxKfrq()+"' kfrq, " +
                "         t1.bis_fixed_costs_ypbm, " +
                "         t1.bis_fixed_costs_mc, " +
                "         t1.bis_fixed_costs_dj, " +
                "         t1.bis_fixed_costs_sl, " +
                "         t1.bis_fixed_costs_zj, " +
                "         t1.bis_fixed_costs_jx, " +
                "         t1.bis_fixed_costs_jl, " +
                "         t1.bis_fixed_costs_sypc, " +
                "         t1.bis_fixed_costs_yf, " +
                "         t1.bis_fixed_costs_zxks, " +
                "         t1.bis_fixed_costs_zxts, " +
                "         t1.BIS_FIXED_COSTS_FWLX, " +
                "         t2.bis_jzdj_ysxm spr, " +
                "         '' jkm, " +
                "         t2.bis_jzdj_ysxm ysxm, " +
                "         t2.bis_jzdj_ysxm jbr, " +
                "         t1.BIS_FIXED_COSTS_FWLX, " +
                "         t1.bis_fixed_costs_dw, " +
                "         t1.bis_fixed_costs_gg, " +
                "         '0' cfybz, " +
                "         1 bzsl, " +
                "         t1.bis_fixed_costs_yl, " +
                "         '' jgm, " +
                "         sysdate, " +
                "         '1' sfyx, " +
                "         t3.bis_zhsq_grbh " +
                "    from BIS_FIXED_COSTS t1, bis_jzdj t2, bis_zhsq t3 " +
                "   where t1.bis_fixed_costs_jzid = t2.bis_jzdj_id " +
                "     and t2.bis_jzdj_zhsq_id = t3.bis_zhsq_id " +
                "     and t2.bis_jzdj_id = :jzid ";
        Query queryOrder = entityManager.createNativeQuery(adlPcSql);

        queryOrder.setParameter("jzid", resources.getBisFymxJzdjId());
        queryOrder.executeUpdate();
    }
}